package com.quantanetwork.esm.port;

import java.io.IOException;

import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.Variable;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;

/**
* Company: QuantaNetwork BeiJing Ltd
* Author : 张彦龙
* DateTime: Nov 26, 2008  12:58:12 PM
*/
public class SnmpIndentifyMethod extends IdentifyMethod
{
	@Override
	public Portinfo indentify(String server, int port, String message, String type, int timeOut)
	{
		Portinfo bean = null;
		Address targetAddress = GenericAddress.parse("udp:" + server + "/" + port);
		CommunityTarget target = new CommunityTarget();
		target.setCommunity(new OctetString("public"));
		target.setAddress(targetAddress);
		target.setTimeout(2000);
		target.setVersion(SnmpConstants.version2c);
		// creating PDU   
		PDU pdu = new PDU();
		pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.1.1.0")));
		pdu.setType(PDU.GET);
		try
		{
			TransportMapping transport = new DefaultUdpTransportMapping();
			transport.listen();
			Snmp snmp = new Snmp(transport);
			ResponseEvent response = snmp.send(pdu, target);
			if (response != null)
			{
				PDU respPdu = response.getResponse();
				if (respPdu != null)
				{
					for (int i = 0; i < respPdu.size(); i++)
					{
						VariableBinding varBinding = respPdu.get(i);
						Variable var = varBinding.getVariable();
						bean = new Portinfo();
						bean.setDesc(var.toString());
					}
				}
			}
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		return bean;
	}
}
